//
//  InputViewController.m
//

#import "InputViewController.h"
#import <Masonry/Masonry.h>
#import "UIColor+Expanded.h"
#import "UITextView+inputAccessry.h"
#import "UITextField+inputAccessry.h"
#import "CustomNavigationController.h"

static NSTimeInterval const kInputViewShakerDefaultDuration = 0.5;
static NSString * const kInputViewShakerAnimationKey = @"kInputViewShakerAnimationKey";

@interface InputViewController ()<UITextFieldDelegate, UITextViewDelegate,CAAnimationDelegate>

@property (nonatomic, copy) InputEnd inputEnd;
@property (strong, nonatomic)  UITextField *textField;
@property (strong, nonatomic)  UITextView *textView;
@property (nonatomic, assign) InputViewType showType;

@property (strong, nonatomic)  UILabel *errorLable;
@property (strong, nonatomic)  UIButton *saveBtn;

@end

@implementation InputViewController

- (instancetype)initWithTilte:(NSString *)tilte withInputType:(InputViewType)type complete:(InputEnd)complete {

    self = [super init];

    if (self) {

        self.customTitel = tilte;
        _showType = type;
        _inputEnd = complete;
        _bottomName = @"Done";
        _maxNumOfString = 0xffff;
    }

    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setupView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (_content.length == 0) {
        return;
    }
    if (_showType == TextFieldType) {
        _textField.text = _content;
    }else{
        _textView.text = _content;
    }
}

- (void)setupView {
    __weak typeof(self) weakSelf = self;
    UIView *contentView = [[UIView alloc] init];
    [self.view addSubview:contentView];
    contentView.backgroundColor = [UIColor colorWithRGBHexString:@"312D3C"];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(@0);
        make.top.equalTo(weakSelf.view.mas_top).offset(0);
        make.bottom.equalTo(@0);
    }];
    
    UIView *textFieldBkView = [[UIView alloc] init];
    [contentView addSubview:textFieldBkView];
    textFieldBkView.layer.cornerRadius = 12;
    textFieldBkView.layer.masksToBounds = YES;
    textFieldBkView.backgroundColor = [UIColor colorWithRGBHexString:@"555164"];
    [textFieldBkView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_safeAreaLayoutGuideTop).offset(21);
        make.leading.equalTo(@11);
        make.trailing.equalTo(@-11);
        make.height.equalTo(@44);
    }];
    
    UITextField *textField = [[UITextField alloc] init];
    [textFieldBkView addSubview:textField];
    textField.font = [UIFont systemFontOfSize:16];
    textField.textColor = [UIColor whiteColor];
    textField.borderStyle = UITextBorderStyleNone;
    textField.textAlignment = NSTextAlignmentLeft;
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 8, 0, 8));
    }];
    _textField = textField;
    
    
    // textView
    UIView *textViewBkView = [[UIView alloc] init];
    [contentView addSubview:textViewBkView];
    textViewBkView.layer.cornerRadius = 12;
    textViewBkView.layer.masksToBounds = YES;
    textViewBkView.backgroundColor = [UIColor colorWithRGBHexString:@"555164"];
    [textViewBkView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_safeAreaLayoutGuideTop).offset(21);
        make.leading.equalTo(@11);
        make.trailing.equalTo(@-11);
        make.height.equalTo(@138);
    }];
    
    UITextView *textView = [[UITextView alloc] init];
    [textViewBkView addSubview:textView];
    textView.font = [UIFont systemFontOfSize:15];
    textView.textColor = [UIColor whiteColor];
    textView.backgroundColor = [UIColor clearColor];
    textView.tintColor = [UIColor colorWithRGBHexString:@"7E1FC9"];
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(5, 5, 5, 5));
    }];
    _textView = textView;
    
    _errorLable = [[UILabel alloc] init];
    [contentView addSubview:_errorLable];
    _errorLable.font = [UIFont systemFontOfSize:14];
    _errorLable.textAlignment = NSTextAlignmentLeft;
    _errorLable.numberOfLines = 0;
    _errorLable.textColor = [UIColor colorWithRGBHexString:@"DB2A08"];
    _errorLable.text = @"";
    _errorLable.hidden = YES;
    [_errorLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_safeAreaLayoutGuideTop).offset((_showType == TextFieldType) ? 76 : 170);
        make.leading.equalTo(@11);make.trailing.equalTo(@-11);
    }];
    
    _saveBtn =[[UIButton alloc] init];
    [contentView addSubview:_saveBtn];
    _saveBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    _saveBtn.backgroundColor = [UIColor colorWithRGBHexString:@"B04DFE"];
    _saveBtn.layer.cornerRadius = 18;
    _saveBtn.layer.masksToBounds = YES;
    [_saveBtn addTarget:self action:@selector(done:) forControlEvents:UIControlEventTouchUpInside];
    [_saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@0);
        make.top.equalTo(weakSelf.errorLable.mas_bottom).offset(37);
        make.width.equalTo(@132);make.height.equalTo(@40);
    }];
    
    _saveBtn.enabled = NO;
    [_saveBtn setTitle:_bottomName forState:UIControlStateNormal];
    if (_showType == TextFieldType) {
        _textField.keyboardType = _keyboardType;
        _textField.superview.hidden = NO;
        _textView.superview.hidden = YES;
        [_textField becomeFirstResponder];
        _textField.maxLength = @(_maxNumOfString);
        if (_placeholder.length>0) {
            _textField.attrPlaceholder = _placeholder;
        }
        _textField.textFieldDidChange = ^(UITextField *textField){
            weakSelf.errorLable.hidden = YES;
            if (textField.text.length <weakSelf.miniNumOfString) {
                weakSelf.saveBtn.enabled = NO;
            } else {
                weakSelf.saveBtn.enabled = YES;
            }
        };
    } else {
        _textField.superview.hidden = YES;
        _textView.superview.hidden = NO;
        _textView.layer.masksToBounds = YES;
        [_textView becomeFirstResponder];
        _textView.maxLength = @(_maxNumOfString);
        if (_placeholder.length>0) {
            _textView.placeholder = _placeholder;
        }
        _textView.space = @(8.0);
        BOOL isRTL = [[[[NSBundle mainBundle] preferredLocalizations] firstObject] hasPrefix:@"ar"];
        _textView.textAlignment = isRTL ? NSTextAlignmentRight : NSTextAlignmentLeft;
        _textView.textViewDidChange = ^(UITextView *textView){
            weakSelf.errorLable.hidden = YES;
           if (textView.text.length <weakSelf.miniNumOfString) {
               weakSelf.saveBtn.enabled = NO;
           } else {
               weakSelf.saveBtn.enabled = YES;
           }
        };
    }

    self.view.backgroundColor = [UIColor colorWithRGBHexString:@"312D3C"];
}

- (void)setBottomName:(NSString *)bottomName {
    _bottomName = bottomName;
    [_saveBtn setTitle:_bottomName forState:UIControlStateNormal];
}

-(void)setContent:(NSString *)content{
    _content = content;
}

- (void)show:(UIViewController *)presentViewCtr {
    CustomNavigationController *navigationInput = [[CustomNavigationController alloc] initWithRootViewController:self];
    [presentViewCtr presentViewController:navigationInput animated:YES completion:nil];
}
- (void)done:(id)sender {
    
    NSString * contentStr =nil;
    
    if (_showType == TextFieldType) {

        [_textField resignFirstResponder];
         _textField.enabled = NO;
        contentStr = _textField.text;

    } else {

        [_textView resignFirstResponder];
        _textView.editable = NO;
        contentStr = _textView.text;
    }
    
    //判断字符
    if (![self filteringCharacteristicsOfCharacter:contentStr]) {
        
        _errorLable.text = _errorMessage;
        _errorLable.hidden = NO;
        _textView.editable = YES;
        _textField.enabled = YES;
        
        //动画提示
        [self addShakeAnimationForView:_errorLable];
        
        return ;
    }
    
    if (_inputEnd) {
        _inputEnd(contentStr);
    }

    [self dismissViewController];
}

- (void)dismissViewController {

    [_textField resignFirstResponder];
    [_textView resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}

//正则过来表达式  返回值为 成立 （YES） 和 不成立 （NO）
- (BOOL)filteringCharacteristicsOfCharacter:(NSString *)character{
    
    if (!_regExFilter) {//_regExFilter为nil 标示不做任何限制
        
        return YES;
    }
    
    if ([character isKindOfClass:[NSString class]]) {
        NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",_regExFilter];
        return [predicate evaluateWithObject:character];
    }
    return NO;
}

//动画部分
- (void)addShakeAnimationForView:(UIView *)view {
    CAKeyframeAnimation * animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.translation.x"];
    animation.delegate = self;
    animation.duration = kInputViewShakerDefaultDuration;
    animation.values = @[ @(0), @(10), @(-8), @(8), @(-5), @(5), @(0) ];
    animation.keyTimes = @[ @(0), @(0.225), @(0.425), @(0.6), @(0.75), @(0.875), @(1) ];
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    [view.layer addAnimation:animation forKey:kInputViewShakerAnimationKey];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
